* (bug 5062) Width sometimes one pixel short when using maximum heights
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 /**
7 * NOTE FOR WINDOWS USERS:
8 * To enable EXIF functions, add the folloing lines to the
9 * "Windows extensions" section of php.ini:
10 *
11 * extension=extensions/php_mbstring.dll
12 * extension=extensions/php_exif.dll
13 */
14
15 if ($wgShowEXIF)
16 require_once('Exif.php');
17
18 /**
19 * Bump this number when serialized cache records may be incompatible.
20 */
21 define( 'MW_IMAGE_VERSION', 1 );
22
23 /**
24 * Class to represent an image
25 *
26 * Provides methods to retrieve paths (physical, logical, URL),
27 * to generate thumbnails or for uploading.
28 * @package MediaWiki
29 */
30 class Image
31 {
32 /**#@+
33 * @access private
34 */
35 var $name, # name of the image (constructor)
36 $imagePath, # Path of the image (loadFromXxx)
37 $url, # Image URL (accessor)
38 $title, # Title object for this image (constructor)
39 $fileExists, # does the image file exist on disk? (loadFromXxx)
40 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
41 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
42 $historyRes, # result of the query for the image's history (nextHistoryLine)
43 $width, # \
44 $height, # |
45 $bits, # --- returned by getimagesize (loadFromXxx)
46 $attr, # /
47 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
48 $mime, # MIME type, determined by MimeMagic::guessMimeType
49 $size, # Size in bytes (loadFromXxx)
50 $metadata, # Metadata
51 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
52 $lastError; # Error string associated with a thumbnail display error
53
54
55 /**#@-*/
56
57 /**
58 * Create an Image object from an image name
59 *
60 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
61 * @access public
62 */
63 function newFromName( $name ) {
64 $title = Title::makeTitleSafe( NS_IMAGE, $name );
65 if ( is_object( $title ) ) {
66 return new Image( $title );
67 } else {
68 return NULL;
69 }
70 }
71
72 /**
73 * Obsolete factory function, use constructor
74 */
75 function newFromTitle( $title ) {
76 return new Image( $title );
77 }
78
79 function Image( $title ) {
80 if( !is_object( $title ) ) {
81 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
82 }
83 $this->title =& $title;
84 $this->name = $title->getDBkey();
85 $this->metadata = serialize ( array() ) ;
86
87 $n = strrpos( $this->name, '.' );
88 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
89 $this->historyLine = 0;
90
91 $this->dataLoaded = false;
92 }
93
94 /**
95 * Get the memcached keys
96 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
97 */
98 function getCacheKeys( $shared = false ) {
99 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
100
101 $foundCached = false;
102 $hashedName = md5($this->name);
103 $keys = array( "$wgDBname:Image:$hashedName" );
104 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
105 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
106 }
107 return $keys;
108 }
109
110 /**
111 * Try to load image metadata from memcached. Returns true on success.
112 */
113 function loadFromCache() {
114 global $wgUseSharedUploads, $wgMemc;
115 $fname = 'Image::loadFromMemcached';
116 wfProfileIn( $fname );
117 $this->dataLoaded = false;
118 $keys = $this->getCacheKeys();
119 $cachedValues = $wgMemc->get( $keys[0] );
120
121 // Check if the key existed and belongs to this version of MediaWiki
122 if (!empty($cachedValues) && is_array($cachedValues)
123 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
124 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
125 {
126 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
127 # if this is shared file, we need to check if image
128 # in shared repository has not changed
129 if ( isset( $keys[1] ) ) {
130 $commonsCachedValues = $wgMemc->get( $keys[1] );
131 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
132 && isset($commonsCachedValues['version'])
133 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
134 && isset($commonsCachedValues['mime'])) {
135 wfDebug( "Pulling image metadata from shared repository cache\n" );
136 $this->name = $commonsCachedValues['name'];
137 $this->imagePath = $commonsCachedValues['imagePath'];
138 $this->fileExists = $commonsCachedValues['fileExists'];
139 $this->width = $commonsCachedValues['width'];
140 $this->height = $commonsCachedValues['height'];
141 $this->bits = $commonsCachedValues['bits'];
142 $this->type = $commonsCachedValues['type'];
143 $this->mime = $commonsCachedValues['mime'];
144 $this->metadata = $commonsCachedValues['metadata'];
145 $this->size = $commonsCachedValues['size'];
146 $this->fromSharedDirectory = true;
147 $this->dataLoaded = true;
148 $this->imagePath = $this->getFullPath(true);
149 }
150 }
151 } else {
152 wfDebug( "Pulling image metadata from local cache\n" );
153 $this->name = $cachedValues['name'];
154 $this->imagePath = $cachedValues['imagePath'];
155 $this->fileExists = $cachedValues['fileExists'];
156 $this->width = $cachedValues['width'];
157 $this->height = $cachedValues['height'];
158 $this->bits = $cachedValues['bits'];
159 $this->type = $cachedValues['type'];
160 $this->mime = $cachedValues['mime'];
161 $this->metadata = $cachedValues['metadata'];
162 $this->size = $cachedValues['size'];
163 $this->fromSharedDirectory = false;
164 $this->dataLoaded = true;
165 $this->imagePath = $this->getFullPath();
166 }
167 }
168 if ( $this->dataLoaded ) {
169 wfIncrStats( 'image_cache_hit' );
170 } else {
171 wfIncrStats( 'image_cache_miss' );
172 }
173
174 wfProfileOut( $fname );
175 return $this->dataLoaded;
176 }
177
178 /**
179 * Save the image metadata to memcached
180 */
181 function saveToCache() {
182 global $wgMemc;
183 $this->load();
184 $keys = $this->getCacheKeys();
185 if ( $this->fileExists ) {
186 // We can't cache negative metadata for non-existent files,
187 // because if the file later appears in commons, the local
188 // keys won't be purged.
189 $cachedValues = array(
190 'version' => MW_IMAGE_VERSION,
191 'name' => $this->name,
192 'imagePath' => $this->imagePath,
193 'fileExists' => $this->fileExists,
194 'fromShared' => $this->fromSharedDirectory,
195 'width' => $this->width,
196 'height' => $this->height,
197 'bits' => $this->bits,
198 'type' => $this->type,
199 'mime' => $this->mime,
200 'metadata' => $this->metadata,
201 'size' => $this->size );
202
203 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
204 } else {
205 // However we should clear them, so they aren't leftover
206 // if we've deleted the file.
207 $wgMemc->delete( $keys[0] );
208 }
209 }
210
211 /**
212 * Load metadata from the file itself
213 */
214 function loadFromFile() {
215 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang,
216 $wgShowEXIF;
217 $fname = 'Image::loadFromFile';
218 wfProfileIn( $fname );
219 $this->imagePath = $this->getFullPath();
220 $this->fileExists = file_exists( $this->imagePath );
221 $this->fromSharedDirectory = false;
222 $gis = array();
223
224 if (!$this->fileExists) wfDebug("$fname: ".$this->imagePath." not found locally!\n");
225
226 # If the file is not found, and a shared upload directory is used, look for it there.
227 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
228 # In case we're on a wgCapitalLinks=false wiki, we
229 # capitalize the first letter of the filename before
230 # looking it up in the shared repository.
231 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
232 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
233 if ( $this->fileExists ) {
234 $this->name = $sharedImage->name;
235 $this->imagePath = $this->getFullPath(true);
236 $this->fromSharedDirectory = true;
237 }
238 }
239
240
241 if ( $this->fileExists ) {
242 $magic=& wfGetMimeMagic();
243
244 $this->mime = $magic->guessMimeType($this->imagePath,true);
245 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
246
247 # Get size in bytes
248 $this->size = filesize( $this->imagePath );
249
250 $magic=& wfGetMimeMagic();
251
252 # Height and width
253 if( $this->mime == 'image/svg' ) {
254 wfSuppressWarnings();
255 $gis = wfGetSVGsize( $this->imagePath );
256 wfRestoreWarnings();
257 }
258 elseif ( !$magic->isPHPImageType( $this->mime ) ) {
259 # Don't try to get the width and height of sound and video files, that's bad for performance
260 $gis[0]= 0; //width
261 $gis[1]= 0; //height
262 $gis[2]= 0; //unknown
263 $gis[3]= ""; //width height string
264 }
265 else {
266 wfSuppressWarnings();
267 $gis = getimagesize( $this->imagePath );
268 wfRestoreWarnings();
269 }
270
271 wfDebug("$fname: ".$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
272 }
273 else {
274 $gis[0]= 0; //width
275 $gis[1]= 0; //height
276 $gis[2]= 0; //unknown
277 $gis[3]= ""; //width height string
278
279 $this->mime = NULL;
280 $this->type = MEDIATYPE_UNKNOWN;
281 wfDebug("$fname: ".$this->imagePath." NOT FOUND!\n");
282 }
283
284 $this->width = $gis[0];
285 $this->height = $gis[1];
286
287 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
288
289 #NOTE: we have to set this flag early to avoid load() to be called
290 # be some of the functions below. This may lead to recursion or other bad things!
291 # as ther's only one thread of execution, this should be safe anyway.
292 $this->dataLoaded = true;
293
294
295 if ($this->fileExists && $wgShowEXIF) $this->metadata = serialize ( $this->retrieveExifData() ) ;
296 else $this->metadata = serialize ( array() ) ;
297
298 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
299 else $this->bits = 0;
300
301 wfProfileOut( $fname );
302 }
303
304 /**
305 * Load image metadata from the DB
306 */
307 function loadFromDB() {
308 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
309 $fname = 'Image::loadFromDB';
310 wfProfileIn( $fname );
311
312 $dbr =& wfGetDB( DB_SLAVE );
313
314 $this->checkDBSchema($dbr);
315
316 $row = $dbr->selectRow( 'image',
317 array( 'img_size', 'img_width', 'img_height', 'img_bits',
318 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
319 array( 'img_name' => $this->name ), $fname );
320 if ( $row ) {
321 $this->fromSharedDirectory = false;
322 $this->fileExists = true;
323 $this->loadFromRow( $row );
324 $this->imagePath = $this->getFullPath();
325 // Check for rows from a previous schema, quietly upgrade them
326 if ( is_null($this->type) ) {
327 $this->upgradeRow();
328 }
329 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
330 # In case we're on a wgCapitalLinks=false wiki, we
331 # capitalize the first letter of the filename before
332 # looking it up in the shared repository.
333 $name = $wgContLang->ucfirst($this->name);
334
335 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
336 array(
337 'img_size', 'img_width', 'img_height', 'img_bits',
338 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
339 array( 'img_name' => $name ), $fname );
340 if ( $row ) {
341 $this->fromSharedDirectory = true;
342 $this->fileExists = true;
343 $this->imagePath = $this->getFullPath(true);
344 $this->name = $name;
345 $this->loadFromRow( $row );
346
347 // Check for rows from a previous schema, quietly upgrade them
348 if ( is_null($this->type) ) {
349 $this->upgradeRow();
350 }
351 }
352 }
353
354 if ( !$row ) {
355 $this->size = 0;
356 $this->width = 0;
357 $this->height = 0;
358 $this->bits = 0;
359 $this->type = 0;
360 $this->fileExists = false;
361 $this->fromSharedDirectory = false;
362 $this->metadata = serialize ( array() ) ;
363 }
364
365 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
366 $this->dataLoaded = true;
367 wfProfileOut( $fname );
368 }
369
370 /*
371 * Load image metadata from a DB result row
372 */
373 function loadFromRow( &$row ) {
374 $this->size = $row->img_size;
375 $this->width = $row->img_width;
376 $this->height = $row->img_height;
377 $this->bits = $row->img_bits;
378 $this->type = $row->img_media_type;
379
380 $major= $row->img_major_mime;
381 $minor= $row->img_minor_mime;
382
383 if (!$major) $this->mime = "unknown/unknown";
384 else {
385 if (!$minor) $minor= "unknown";
386 $this->mime = $major.'/'.$minor;
387 }
388
389 $this->metadata = $row->img_metadata;
390 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
391
392 $this->dataLoaded = true;
393 }
394
395 /**
396 * Load image metadata from cache or DB, unless already loaded
397 */
398 function load() {
399 global $wgSharedUploadDBname, $wgUseSharedUploads;
400 if ( !$this->dataLoaded ) {
401 if ( !$this->loadFromCache() ) {
402 $this->loadFromDB();
403 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
404 $this->loadFromFile();
405 } elseif ( $this->fileExists ) {
406 $this->saveToCache();
407 }
408 }
409 $this->dataLoaded = true;
410 }
411 }
412
413 /**
414 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
415 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
416 */
417 function upgradeRow() {
418 global $wgDBname, $wgSharedUploadDBname;
419 $fname = 'Image::upgradeRow';
420 wfProfileIn( $fname );
421
422 $this->loadFromFile();
423 $dbw =& wfGetDB( DB_MASTER );
424
425 if ( $this->fromSharedDirectory ) {
426 if ( !$wgSharedUploadDBname ) {
427 wfProfileOut( $fname );
428 return;
429 }
430
431 // Write to the other DB using selectDB, not database selectors
432 // This avoids breaking replication in MySQL
433 $dbw->selectDB( $wgSharedUploadDBname );
434 }
435
436 $this->checkDBSchema($dbw);
437
438 if (strpos($this->mime,'/')!==false) {
439 list($major,$minor)= explode('/',$this->mime,2);
440 }
441 else {
442 $major= $this->mime;
443 $minor= "unknown";
444 }
445
446 wfDebug("$fname: upgrading ".$this->name." to 1.5 schema\n");
447
448 $dbw->update( 'image',
449 array(
450 'img_width' => $this->width,
451 'img_height' => $this->height,
452 'img_bits' => $this->bits,
453 'img_media_type' => $this->type,
454 'img_major_mime' => $major,
455 'img_minor_mime' => $minor,
456 'img_metadata' => $this->metadata,
457 ), array( 'img_name' => $this->name ), $fname
458 );
459 if ( $this->fromSharedDirectory ) {
460 $dbw->selectDB( $wgDBname );
461 }
462 wfProfileOut( $fname );
463 }
464
465 /**
466 * Return the name of this image
467 * @access public
468 */
469 function getName() {
470 return $this->name;
471 }
472
473 /**
474 * Return the associated title object
475 * @access public
476 */
477 function getTitle() {
478 return $this->title;
479 }
480
481 /**
482 * Return the URL of the image file
483 * @access public
484 */
485 function getURL() {
486 if ( !$this->url ) {
487 $this->load();
488 if($this->fileExists) {
489 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
490 } else {
491 $this->url = '';
492 }
493 }
494 return $this->url;
495 }
496
497 function getViewURL() {
498 if( $this->mustRender()) {
499 if( $this->canRender() ) {
500 return $this->createThumb( $this->getWidth() );
501 }
502 else {
503 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
504 return $this->getURL(); #hm... return NULL?
505 }
506 } else {
507 return $this->getURL();
508 }
509 }
510
511 /**
512 * Return the image path of the image in the
513 * local file system as an absolute path
514 * @access public
515 */
516 function getImagePath() {
517 $this->load();
518 return $this->imagePath;
519 }
520
521 /**
522 * Return the width of the image
523 *
524 * Returns -1 if the file specified is not a known image type
525 * @access public
526 */
527 function getWidth() {
528 $this->load();
529 return $this->width;
530 }
531
532 /**
533 * Return the height of the image
534 *
535 * Returns -1 if the file specified is not a known image type
536 * @access public
537 */
538 function getHeight() {
539 $this->load();
540 return $this->height;
541 }
542
543 /**
544 * Return the size of the image file, in bytes
545 * @access public
546 */
547 function getSize() {
548 $this->load();
549 return $this->size;
550 }
551
552 /**
553 * Returns the mime type of the file.
554 */
555 function getMimeType() {
556 $this->load();
557 return $this->mime;
558 }
559
560 /**
561 * Return the type of the media in the file.
562 * Use the value returned by this function with the MEDIATYPE_xxx constants.
563 */
564 function getMediaType() {
565 $this->load();
566 return $this->type;
567 }
568
569 /**
570 * Checks if the file can be presented to the browser as a bitmap.
571 *
572 * Currently, this checks if the file is an image format
573 * that can be converted to a format
574 * supported by all browsers (namely GIF, PNG and JPEG),
575 * or if it is an SVG image and SVG conversion is enabled.
576 *
577 * @todo remember the result of this check.
578 */
579 function canRender() {
580 global $wgUseImageMagick;
581
582 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
583
584 $mime= $this->getMimeType();
585
586 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
587
588 #if it's SVG, check if there's a converter enabled
589 if ($mime === 'image/svg') {
590 global $wgSVGConverters, $wgSVGConverter;
591
592 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
593 wfDebug( "Image::canRender: SVG is ready!\n" );
594 return true;
595 } else {
596 wfDebug( "Image::canRender: SVG renderer missing\n" );
597 }
598 }
599
600 #image formats available on ALL browsers
601 if ( $mime === 'image/gif'
602 || $mime === 'image/png'
603 || $mime === 'image/jpeg' ) return true;
604
605 #image formats that can be converted to the above formats
606 if ($wgUseImageMagick) {
607 #convertable by ImageMagick (there are more...)
608 if ( $mime === 'image/vnd.wap.wbmp'
609 || $mime === 'image/x-xbitmap'
610 || $mime === 'image/x-xpixmap'
611 #|| $mime === 'image/x-icon' #file may be split into multiple parts
612 || $mime === 'image/x-portable-anymap'
613 || $mime === 'image/x-portable-bitmap'
614 || $mime === 'image/x-portable-graymap'
615 || $mime === 'image/x-portable-pixmap'
616 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
617 || $mime === 'image/x-rgb'
618 || $mime === 'image/x-bmp'
619 || $mime === 'image/tiff' ) return true;
620 }
621 else {
622 #convertable by the PHP GD image lib
623 if ( $mime === 'image/vnd.wap.wbmp'
624 || $mime === 'image/x-xbitmap' ) return true;
625 }
626
627 return false;
628 }
629
630
631 /**
632 * Return true if the file is of a type that can't be directly
633 * rendered by typical browsers and needs to be re-rasterized.
634 *
635 * This returns true for everything but the bitmap types
636 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
637 * also return true for any non-image formats.
638 *
639 * @return bool
640 */
641 function mustRender() {
642 $mime= $this->getMimeType();
643
644 if ( $mime === "image/gif"
645 || $mime === "image/png"
646 || $mime === "image/jpeg" ) return false;
647
648 return true;
649 }
650
651 /**
652 * Determines if this media file may be shown inline on a page.
653 *
654 * This is currently synonymous to canRender(), but this could be
655 * extended to also allow inline display of other media,
656 * like flash animations or videos. If you do so, please keep in mind that
657 * that could be a security risk.
658 */
659 function allowInlineDisplay() {
660 return $this->canRender();
661 }
662
663 /**
664 * Determines if this media file is in a format that is unlikely to
665 * contain viruses or malicious content. It uses the global
666 * $wgTrustedMediaFormats list to determine if the file is safe.
667 *
668 * This is used to show a warning on the description page of non-safe files.
669 * It may also be used to disallow direct [[media:...]] links to such files.
670 *
671 * Note that this function will always return true if allowInlineDisplay()
672 * or isTrustedFile() is true for this file.
673 */
674 function isSafeFile() {
675 if ($this->allowInlineDisplay()) return true;
676 if ($this->isTrustedFile()) return true;
677
678 global $wgTrustedMediaFormats;
679
680 $type= $this->getMediaType();
681 $mime= $this->getMimeType();
682 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
683
684 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
685 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
686
687 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
688 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
689
690 return false;
691 }
692
693 /** Returns true if the file is flagged as trusted. Files flagged that way
694 * can be linked to directly, even if that is not allowed for this type of
695 * file normally.
696 *
697 * This is a dummy function right now and always returns false. It could be
698 * implemented to extract a flag from the database. The trusted flag could be
699 * set on upload, if the user has sufficient privileges, to bypass script-
700 * and html-filters. It may even be coupled with cryptographics signatures
701 * or such.
702 */
703 function isTrustedFile() {
704 #this could be implemented to check a flag in the databas,
705 #look for signatures, etc
706 return false;
707 }
708
709 /**
710 * Return the escapeLocalURL of this image
711 * @access public
712 */
713 function getEscapeLocalURL() {
714 $this->getTitle();
715 return $this->title->escapeLocalURL();
716 }
717
718 /**
719 * Return the escapeFullURL of this image
720 * @access public
721 */
722 function getEscapeFullURL() {
723 $this->getTitle();
724 return $this->title->escapeFullURL();
725 }
726
727 /**
728 * Return the URL of an image, provided its name.
729 *
730 * @param string $name Name of the image, without the leading "Image:"
731 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
732 * @return string URL of $name image
733 * @access public
734 * @static
735 */
736 function imageUrl( $name, $fromSharedDirectory = false ) {
737 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
738 if($fromSharedDirectory) {
739 $base = '';
740 $path = $wgSharedUploadPath;
741 } else {
742 $base = $wgUploadBaseUrl;
743 $path = $wgUploadPath;
744 }
745 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
746 return wfUrlencode( $url );
747 }
748
749 /**
750 * Returns true if the image file exists on disk.
751 * @return boolean Whether image file exist on disk.
752 * @access public
753 */
754 function exists() {
755 $this->load();
756 return $this->fileExists;
757 }
758
759 /**
760 * @todo document
761 * @access private
762 */
763 function thumbUrl( $width, $subdir='thumb') {
764 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
765 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
766
767 // Generate thumb.php URL if possible
768 $script = false;
769 $url = false;
770
771 if ( $this->fromSharedDirectory ) {
772 if ( $wgSharedThumbnailScriptPath ) {
773 $script = $wgSharedThumbnailScriptPath;
774 }
775 } else {
776 if ( $wgThumbnailScriptPath ) {
777 $script = $wgThumbnailScriptPath;
778 }
779 }
780 if ( $script ) {
781 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
782 if( $this->mustRender() ) {
783 $url.= '&r=1';
784 }
785 } else {
786 $name = $this->thumbName( $width );
787 if($this->fromSharedDirectory) {
788 $base = '';
789 $path = $wgSharedUploadPath;
790 } else {
791 $base = $wgUploadBaseUrl;
792 $path = $wgUploadPath;
793 }
794 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
795 $url = "{$base}{$path}/{$subdir}" .
796 wfGetHashPath($this->name, $this->fromSharedDirectory)
797 . $this->name.'/'.$name;
798 $url = wfUrlencode( $url );
799 } else {
800 $url = "{$base}{$path}/{$subdir}/{$name}";
801 }
802 }
803 return array( $script !== false, $url );
804 }
805
806 /**
807 * Return the file name of a thumbnail of the specified width
808 *
809 * @param integer $width Width of the thumbnail image
810 * @param boolean $shared Does the thumbnail come from the shared repository?
811 * @access private
812 */
813 function thumbName( $width ) {
814 $thumb = $width."px-".$this->name;
815
816 if( $this->mustRender() ) {
817 if( $this->canRender() ) {
818 # Rasterize to PNG (for SVG vector images, etc)
819 $thumb .= '.png';
820 }
821 else {
822 #should we use iconThumb here to get a symbolic thumbnail?
823 #or should we fail with an internal error?
824 return NULL; //can't make bitmap
825 }
826 }
827 return $thumb;
828 }
829
830 /**
831 * Create a thumbnail of the image having the specified width/height.
832 * The thumbnail will not be created if the width is larger than the
833 * image's width. Let the browser do the scaling in this case.
834 * The thumbnail is stored on disk and is only computed if the thumbnail
835 * file does not exist OR if it is older than the image.
836 * Returns the URL.
837 *
838 * Keeps aspect ratio of original image. If both width and height are
839 * specified, the generated image will be no bigger than width x height,
840 * and will also have correct aspect ratio.
841 *
842 * @param integer $width maximum width of the generated thumbnail
843 * @param integer $height maximum height of the image (optional)
844 * @access public
845 */
846 function createThumb( $width, $height=-1 ) {
847 $thumb = $this->getThumbnail( $width, $height );
848 if( is_null( $thumb ) ) return '';
849 return $thumb->getUrl();
850 }
851
852 /**
853 * As createThumb, but returns a ThumbnailImage object. This can
854 * provide access to the actual file, the real size of the thumb,
855 * and can produce a convenient <img> tag for you.
856 *
857 * @param integer $width maximum width of the generated thumbnail
858 * @param integer $height maximum height of the image (optional)
859 * @return ThumbnailImage
860 * @access public
861 */
862 function getThumbnail( $width, $height=-1 ) {
863 if ( $height <= 0 ) {
864 return $this->renderThumb( $width );
865 }
866 $this->load();
867
868 if ($this->canRender()) {
869 if ( $width > $this->width * $height / $this->height )
870 $width = wfFitBoxWidth( $this->width, $this->height, $height );
871 $thumb = $this->renderThumb( $width );
872 }
873 else $thumb= NULL; #not a bitmap or renderable image, don't try.
874
875 if( is_null( $thumb ) ) {
876 $thumb = $this->iconThumb();
877 }
878 return $thumb;
879 }
880
881 /**
882 * @return ThumbnailImage
883 */
884 function iconThumb() {
885 global $wgStylePath, $wgStyleDirectory;
886
887 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
888 foreach( $try as $icon ) {
889 $path = '/common/images/icons/' . $icon;
890 $filepath = $wgStyleDirectory . $path;
891 if( file_exists( $filepath ) ) {
892 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
893 }
894 }
895 return null;
896 }
897
898 /**
899 * Create a thumbnail of the image having the specified width.
900 * The thumbnail will not be created if the width is larger than the
901 * image's width. Let the browser do the scaling in this case.
902 * The thumbnail is stored on disk and is only computed if the thumbnail
903 * file does not exist OR if it is older than the image.
904 * Returns an object which can return the pathname, URL, and physical
905 * pixel size of the thumbnail -- or null on failure.
906 *
907 * @return ThumbnailImage
908 * @access private
909 */
910 function renderThumb( $width, $useScript = true ) {
911 global $wgUseSquid, $wgInternalServer;
912 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
913 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
914
915 $fname = 'Image::renderThumb';
916 wfProfileIn( $fname );
917
918 $width = intval( $width );
919
920 $this->load();
921 if ( ! $this->exists() )
922 {
923 # If there is no image, there will be no thumbnail
924 wfProfileOut( $fname );
925 return null;
926 }
927
928 # Sanity check $width
929 if( $width <= 0 || $this->width <= 0) {
930 # BZZZT
931 wfProfileOut( $fname );
932 return null;
933 }
934
935 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
936 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
937 # an exception for it.
938 if ( $this->getMediaType() == MEDIATYPE_BITMAP &&
939 $this->getMimeType() !== 'image/jpeg' &&
940 $this->width * $this->height > $wgMaxImageArea )
941 {
942 wfProfileOut( $fname );
943 return null;
944 }
945
946 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
947 if ( $this->mustRender() ) {
948 $width = min( $width, $wgSVGMaxSize );
949 } elseif ( $width > $this->width - 1 ) {
950 $thumb = new ThumbnailImage( $this->getURL(), $this->getWidth(), $this->getHeight() );
951 wfProfileOut( $fname );
952 return $thumb;
953 }
954
955 $height = round( $this->height * $width / $this->width );
956
957 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
958 if ( $isScriptUrl && $useScript ) {
959 // Use thumb.php to render the image
960 $thumb = new ThumbnailImage( $url, $width, $height );
961 wfProfileOut( $fname );
962 return $thumb;
963 }
964
965 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
966 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
967
968 if ( is_dir( $thumbPath ) ) {
969 // Directory where file should be
970 // This happened occasionally due to broken migration code in 1.5
971 // Rename to broken-*
972 global $wgUploadDirectory;
973 for ( $i = 0; $i < 100 ; $i++ ) {
974 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
975 if ( !file_exists( $broken ) ) {
976 rename( $thumbPath, $broken );
977 break;
978 }
979 }
980 // Code below will ask if it exists, and the answer is now no
981 clearstatcache();
982 }
983
984 $done = true;
985 if ( !file_exists( $thumbPath ) ||
986 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX, $wgThumbnailEpoch ) ) {
987 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
988 '/'.$thumbName;
989 $done = false;
990
991 // Migration from old directory structure
992 if ( is_file( $oldThumbPath ) ) {
993 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
994 if ( file_exists( $thumbPath ) ) {
995 if ( !is_dir( $thumbPath ) ) {
996 // Old image in the way of rename
997 unlink( $thumbPath );
998 } else {
999 // This should have been dealt with already
1000 wfDebugDieBacktrace( "Directory where image should be: $thumbPath" );
1001 }
1002 }
1003 // Rename the old image into the new location
1004 rename( $oldThumbPath, $thumbPath );
1005 $done = true;
1006 } else {
1007 unlink( $oldThumbPath );
1008 }
1009 }
1010 if ( !$done ) {
1011 $this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
1012 if ( $this->lastError === true ) {
1013 $done = true;
1014 }
1015
1016 # Purge squid
1017 # This has to be done after the image is updated and present for all machines on NFS,
1018 # or else the old version might be stored into the squid again
1019 if ( $wgUseSquid ) {
1020 if ( substr( $url, 0, 4 ) == 'http' ) {
1021 $urlArr = array( $url );
1022 } else {
1023 $urlArr = array( $wgInternalServer.$url );
1024 }
1025 wfPurgeSquidServers($urlArr);
1026 }
1027 }
1028 }
1029
1030 if ( $done ) {
1031 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1032 } else {
1033 $thumb = null;
1034 }
1035 wfProfileOut( $fname );
1036 return $thumb;
1037 } // END OF function renderThumb
1038
1039 /**
1040 * Really render a thumbnail
1041 * Call this only for images for which canRender() returns true.
1042 *
1043 * @param string $thumbPath Path to thumbnail
1044 * @param int $width Desired width in pixels
1045 * @param int $height Desired height in pixels
1046 * @return bool True on error, false or error string on failure.
1047 * @access private
1048 */
1049 function reallyRenderThumb( $thumbPath, $width, $height ) {
1050 global $wgSVGConverters, $wgSVGConverter,
1051 $wgUseImageMagick, $wgImageMagickConvertCommand;
1052
1053 $this->load();
1054
1055 $err = false;
1056 if( $this->mime === "image/svg" ) {
1057 #Right now we have only SVG
1058
1059 global $wgSVGConverters, $wgSVGConverter;
1060 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1061 global $wgSVGConverterPath;
1062 $cmd = str_replace(
1063 array( '$path/', '$width', '$height', '$input', '$output' ),
1064 array( $wgSVGConverterPath ? "$wgSVGConverterPath/" : "",
1065 intval( $width ),
1066 intval( $height ),
1067 wfEscapeShellArg( $this->imagePath ),
1068 wfEscapeShellArg( $thumbPath ) ),
1069 $wgSVGConverters[$wgSVGConverter] );
1070 wfProfileIn( 'rsvg' );
1071 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1072 $err = wfShellExec( $cmd );
1073 wfProfileOut( 'rsvg' );
1074 }
1075 } elseif ( $wgUseImageMagick ) {
1076 # use ImageMagick
1077
1078 if ( $this->mime == 'image/jpeg' ) {
1079 $quality = "-quality 80"; // 80%
1080 } elseif ( $this->mime == 'image/png' ) {
1081 $quality = "-quality 95"; // zlib 9, adaptive filtering
1082 } else {
1083 $quality = ''; // default
1084 }
1085
1086 # Specify white background color, will be used for transparent images
1087 # in Internet Explorer/Windows instead of default black.
1088
1089 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1090 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1091 # the wrong size in the second case.
1092
1093 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1094 " {$quality} -background white -size {$width} ".
1095 wfEscapeShellArg($this->imagePath) .
1096 // For the -resize option a "!" is needed to force exact size,
1097 // or ImageMagick may decide your ratio is wrong and slice off
1098 // a pixel.
1099 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1100 " -depth 8 " .
1101 wfEscapeShellArg($thumbPath) . " 2>&1";
1102 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1103 wfProfileIn( 'convert' );
1104 $err = wfShellExec( $cmd );
1105 wfProfileOut( 'convert' );
1106 } else {
1107 # Use PHP's builtin GD library functions.
1108 #
1109 # First find out what kind of file this is, and select the correct
1110 # input routine for this.
1111
1112 $typemap = array(
1113 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1114 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1115 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1116 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1117 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1118 );
1119 if( !isset( $typemap[$this->mime] ) ) {
1120 $err = 'Image type not supported';
1121 wfDebug( "$err\n" );
1122 return $err;
1123 }
1124 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1125
1126 if( !function_exists( $loader ) ) {
1127 $err = "Incomplete GD library configuration: missing function $loader";
1128 wfDebug( "$err\n" );
1129 return $err;
1130 }
1131 if( $colorStyle == 'palette' ) {
1132 $truecolor = false;
1133 } elseif( $colorStyle == 'truecolor' ) {
1134 $truecolor = true;
1135 } elseif( $colorStyle == 'bits' ) {
1136 $truecolor = ( $this->bits > 8 );
1137 }
1138
1139 $src_image = call_user_func( $loader, $this->imagePath );
1140 if ( $truecolor ) {
1141 $dst_image = imagecreatetruecolor( $width, $height );
1142 } else {
1143 $dst_image = imagecreate( $width, $height );
1144 }
1145 imagecopyresampled( $dst_image, $src_image,
1146 0,0,0,0,
1147 $width, $height, $this->width, $this->height );
1148 call_user_func( $saveType, $dst_image, $thumbPath );
1149 imagedestroy( $dst_image );
1150 imagedestroy( $src_image );
1151 }
1152
1153 #
1154 # Check for zero-sized thumbnails. Those can be generated when
1155 # no disk space is available or some other error occurs
1156 #
1157 if( file_exists( $thumbPath ) ) {
1158 $thumbstat = stat( $thumbPath );
1159 if( $thumbstat['size'] == 0 ) {
1160 unlink( $thumbPath );
1161 } else {
1162 // All good
1163 $err = true;
1164 }
1165 }
1166 if ( $err !== true ) {
1167 return wfMsg( 'thumbnail_error', $err );
1168 } else {
1169 return true;
1170 }
1171 }
1172
1173 function getLastError() {
1174 return $this->lastError;
1175 }
1176
1177 function imageJpegWrapper( $dst_image, $thumbPath ) {
1178 imageinterlace( $dst_image );
1179 imagejpeg( $dst_image, $thumbPath, 95 );
1180 }
1181
1182 /**
1183 * Get all thumbnail names previously generated for this image
1184 */
1185 function getThumbnails( $shared = false ) {
1186 if ( Image::isHashed( $shared ) ) {
1187 $this->load();
1188 $files = array();
1189 $dir = wfImageThumbDir( $this->name, $shared );
1190
1191 // This generates an error on failure, hence the @
1192 $handle = @opendir( $dir );
1193
1194 if ( $handle ) {
1195 while ( false !== ( $file = readdir($handle) ) ) {
1196 if ( $file{0} != '.' ) {
1197 $files[] = $file;
1198 }
1199 }
1200 closedir( $handle );
1201 }
1202 } else {
1203 $files = array();
1204 }
1205
1206 return $files;
1207 }
1208
1209 /**
1210 * Refresh metadata in memcached, but don't touch thumbnails or squid
1211 */
1212 function purgeMetadataCache() {
1213 clearstatcache();
1214 $this->loadFromFile();
1215 $this->saveToCache();
1216 }
1217
1218 /**
1219 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1220 */
1221 function purgeCache( $archiveFiles = array(), $shared = false ) {
1222 global $wgInternalServer, $wgUseSquid;
1223
1224 // Refresh metadata cache
1225 $this->purgeMetadataCache();
1226
1227 // Delete thumbnails
1228 $files = $this->getThumbnails( $shared );
1229 $dir = wfImageThumbDir( $this->name, $shared );
1230 $urls = array();
1231 foreach ( $files as $file ) {
1232 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1233 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1234 @unlink( "$dir/$file" );
1235 }
1236 }
1237
1238 // Purge the squid
1239 if ( $wgUseSquid ) {
1240 $urls[] = $wgInternalServer . $this->getViewURL();
1241 foreach ( $archiveFiles as $file ) {
1242 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1243 }
1244 wfPurgeSquidServers( $urls );
1245 }
1246 }
1247
1248 function checkDBSchema(&$db) {
1249 global $wgCheckDBSchema;
1250 if (!$wgCheckDBSchema) {
1251 return;
1252 }
1253 # img_name must be unique
1254 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1255 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1256 }
1257
1258 #new fields must exist
1259 if ( !$db->fieldExists( 'image', 'img_media_type' )
1260 || !$db->fieldExists( 'image', 'img_metadata' )
1261 || !$db->fieldExists( 'image', 'img_width' ) ) {
1262
1263 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1264 }
1265 }
1266
1267 /**
1268 * Return the image history of this image, line by line.
1269 * starts with current version, then old versions.
1270 * uses $this->historyLine to check which line to return:
1271 * 0 return line for current version
1272 * 1 query for old versions, return first one
1273 * 2, ... return next old version from above query
1274 *
1275 * @access public
1276 */
1277 function nextHistoryLine() {
1278 $fname = 'Image::nextHistoryLine()';
1279 $dbr =& wfGetDB( DB_SLAVE );
1280
1281 $this->checkDBSchema($dbr);
1282
1283 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1284 $this->historyRes = $dbr->select( 'image',
1285 array(
1286 'img_size',
1287 'img_description',
1288 'img_user','img_user_text',
1289 'img_timestamp',
1290 'img_width',
1291 'img_height',
1292 "'' AS oi_archive_name"
1293 ),
1294 array( 'img_name' => $this->title->getDBkey() ),
1295 $fname
1296 );
1297 if ( 0 == wfNumRows( $this->historyRes ) ) {
1298 return FALSE;
1299 }
1300 } else if ( $this->historyLine == 1 ) {
1301 $this->historyRes = $dbr->select( 'oldimage',
1302 array(
1303 'oi_size AS img_size',
1304 'oi_description AS img_description',
1305 'oi_user AS img_user',
1306 'oi_user_text AS img_user_text',
1307 'oi_timestamp AS img_timestamp',
1308 'oi_width as img_width',
1309 'oi_height as img_height',
1310 'oi_archive_name'
1311 ),
1312 array( 'oi_name' => $this->title->getDBkey() ),
1313 $fname,
1314 array( 'ORDER BY' => 'oi_timestamp DESC' )
1315 );
1316 }
1317 $this->historyLine ++;
1318
1319 return $dbr->fetchObject( $this->historyRes );
1320 }
1321
1322 /**
1323 * Reset the history pointer to the first element of the history
1324 * @access public
1325 */
1326 function resetHistory() {
1327 $this->historyLine = 0;
1328 }
1329
1330 /**
1331 * Return the full filesystem path to the file. Note that this does
1332 * not mean that a file actually exists under that location.
1333 *
1334 * This path depends on whether directory hashing is active or not,
1335 * i.e. whether the images are all found in the same directory,
1336 * or in hashed paths like /images/3/3c.
1337 *
1338 * @access public
1339 * @param boolean $fromSharedDirectory Return the path to the file
1340 * in a shared repository (see $wgUseSharedRepository and related
1341 * options in DefaultSettings.php) instead of a local one.
1342 *
1343 */
1344 function getFullPath( $fromSharedRepository = false ) {
1345 global $wgUploadDirectory, $wgSharedUploadDirectory;
1346
1347 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1348 $wgUploadDirectory;
1349
1350 // $wgSharedUploadDirectory may be false, if thumb.php is used
1351 if ( $dir ) {
1352 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1353 } else {
1354 $fullpath = false;
1355 }
1356
1357 return $fullpath;
1358 }
1359
1360 /**
1361 * @return bool
1362 * @static
1363 */
1364 function isHashed( $shared ) {
1365 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1366 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1367 }
1368
1369 /**
1370 * Record an image upload in the upload log and the image table
1371 */
1372 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1373 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1374
1375 $fname = 'Image::recordUpload';
1376 $dbw =& wfGetDB( DB_MASTER );
1377
1378 $this->checkDBSchema($dbw);
1379
1380 // Delete thumbnails and refresh the metadata cache
1381 $this->purgeCache();
1382
1383 // Fail now if the image isn't there
1384 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1385 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1386 return false;
1387 }
1388
1389 if ( $wgUseCopyrightUpload ) {
1390 if ( $license != '' ) {
1391 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1392 }
1393 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1394 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1395 "$licensetxt" .
1396 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1397 } else {
1398 if ( $license != '' ) {
1399 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1400 $textdesc = $filedesc .
1401 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1402 } else {
1403 $textdesc = $desc;
1404 }
1405 }
1406
1407 $now = $dbw->timestamp();
1408
1409 #split mime type
1410 if (strpos($this->mime,'/')!==false) {
1411 list($major,$minor)= explode('/',$this->mime,2);
1412 }
1413 else {
1414 $major= $this->mime;
1415 $minor= "unknown";
1416 }
1417
1418 # Test to see if the row exists using INSERT IGNORE
1419 # This avoids race conditions by locking the row until the commit, and also
1420 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1421 $dbw->insert( 'image',
1422 array(
1423 'img_name' => $this->name,
1424 'img_size'=> $this->size,
1425 'img_width' => intval( $this->width ),
1426 'img_height' => intval( $this->height ),
1427 'img_bits' => $this->bits,
1428 'img_media_type' => $this->type,
1429 'img_major_mime' => $major,
1430 'img_minor_mime' => $minor,
1431 'img_timestamp' => $now,
1432 'img_description' => $desc,
1433 'img_user' => $wgUser->getID(),
1434 'img_user_text' => $wgUser->getName(),
1435 'img_metadata' => $this->metadata,
1436 ),
1437 $fname,
1438 'IGNORE'
1439 );
1440 $descTitle = $this->getTitle();
1441 $purgeURLs = array();
1442
1443 if( $dbw->affectedRows() == 0 ) {
1444 # Collision, this is an update of an image
1445 # Insert previous contents into oldimage
1446 $dbw->insertSelect( 'oldimage', 'image',
1447 array(
1448 'oi_name' => 'img_name',
1449 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1450 'oi_size' => 'img_size',
1451 'oi_width' => 'img_width',
1452 'oi_height' => 'img_height',
1453 'oi_bits' => 'img_bits',
1454 'oi_timestamp' => 'img_timestamp',
1455 'oi_description' => 'img_description',
1456 'oi_user' => 'img_user',
1457 'oi_user_text' => 'img_user_text',
1458 ), array( 'img_name' => $this->name ), $fname
1459 );
1460
1461 # Update the current image row
1462 $dbw->update( 'image',
1463 array( /* SET */
1464 'img_size' => $this->size,
1465 'img_width' => intval( $this->width ),
1466 'img_height' => intval( $this->height ),
1467 'img_bits' => $this->bits,
1468 'img_media_type' => $this->type,
1469 'img_major_mime' => $major,
1470 'img_minor_mime' => $minor,
1471 'img_timestamp' => $now,
1472 'img_description' => $desc,
1473 'img_user' => $wgUser->getID(),
1474 'img_user_text' => $wgUser->getName(),
1475 'img_metadata' => $this->metadata,
1476 ), array( /* WHERE */
1477 'img_name' => $this->name
1478 ), $fname
1479 );
1480 }
1481
1482 $article = new Article( $descTitle );
1483 $minor = false;
1484 $watch = $watch || $wgUser->isWatched( $descTitle );
1485 $suppressRC = true; // There's already a log entry, so don't double the RC load
1486
1487 if( $descTitle->exists() ) {
1488 // TODO: insert a null revision into the page history for this update.
1489 if( $watch ) {
1490 $wgUser->addWatch( $descTitle );
1491 }
1492
1493 # Invalidate the cache for the description page
1494 $descTitle->invalidateCache();
1495 $purgeURLs[] = $descTitle->getInternalURL();
1496 } else {
1497 // New image; create the description page.
1498 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1499 }
1500
1501 # Invalidate cache for all pages using this image
1502 $linksTo = $this->getLinksTo();
1503
1504 if ( $wgUseSquid ) {
1505 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1506 array_push( $wgPostCommitUpdateList, $u );
1507 }
1508 Title::touchArray( $linksTo );
1509
1510 $log = new LogPage( 'upload' );
1511 $log->addEntry( 'upload', $descTitle, $desc );
1512
1513 return true;
1514 }
1515
1516 /**
1517 * Get an array of Title objects which are articles which use this image
1518 * Also adds their IDs to the link cache
1519 *
1520 * This is mostly copied from Title::getLinksTo()
1521 */
1522 function getLinksTo( $options = '' ) {
1523 $fname = 'Image::getLinksTo';
1524 wfProfileIn( $fname );
1525
1526 if ( $options ) {
1527 $db =& wfGetDB( DB_MASTER );
1528 } else {
1529 $db =& wfGetDB( DB_SLAVE );
1530 }
1531 $linkCache =& LinkCache::singleton();
1532
1533 extract( $db->tableNames( 'page', 'imagelinks' ) );
1534 $encName = $db->addQuotes( $this->name );
1535 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1536 $res = $db->query( $sql, $fname );
1537
1538 $retVal = array();
1539 if ( $db->numRows( $res ) ) {
1540 while ( $row = $db->fetchObject( $res ) ) {
1541 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1542 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1543 $retVal[] = $titleObj;
1544 }
1545 }
1546 }
1547 $db->freeResult( $res );
1548 wfProfileOut( $fname );
1549 return $retVal;
1550 }
1551 /**
1552 * Retrive Exif data from the database
1553 *
1554 * Retrive Exif data from the database and prune unrecognized tags
1555 * and/or tags with invalid contents
1556 *
1557 * @return array
1558 */
1559 function retrieveExifData() {
1560 if ( $this->getMimeType() !== "image/jpeg" )
1561 return array();
1562
1563 $exif = new Exif( $this->imagePath );
1564 return $exif->getFilteredData();
1565 }
1566
1567 function getExifData() {
1568 global $wgRequest;
1569 if ( $this->metadata === '0' )
1570 return array();
1571
1572 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1573 $ret = unserialize( $this->metadata );
1574
1575 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1576 $newver = Exif::version();
1577
1578 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1579 $this->purgeMetadataCache();
1580 $this->updateExifData( $newver );
1581 }
1582 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1583 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1584 $format = new FormatExif( $ret );
1585
1586 return $format->getFormattedData();
1587 }
1588
1589 function updateExifData( $version ) {
1590 $fname = 'Image:updateExifData';
1591
1592 if ( $this->getImagePath() === false ) # Not a local image
1593 return;
1594
1595 # Get EXIF data from image
1596 $exif = $this->retrieveExifData();
1597 if ( count( $exif ) ) {
1598 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1599 $this->metadata = serialize( $exif );
1600 } else {
1601 $this->metadata = '0';
1602 }
1603
1604 # Update EXIF data in database
1605 $dbw =& wfGetDB( DB_MASTER );
1606
1607 $this->checkDBSchema($dbw);
1608
1609 $dbw->update( 'image',
1610 array( 'img_metadata' => $this->metadata ),
1611 array( 'img_name' => $this->name ),
1612 $fname
1613 );
1614 }
1615
1616 /**
1617 * Returns true if the image does not come from the shared
1618 * image repository.
1619 *
1620 * @return bool
1621 */
1622 function isLocal() {
1623 return !$this->fromSharedDirectory;
1624 }
1625
1626 } //class
1627
1628
1629 /**
1630 * Returns the image directory of an image
1631 * If the directory does not exist, it is created.
1632 * The result is an absolute path.
1633 *
1634 * This function is called from thumb.php before Setup.php is included
1635 *
1636 * @param string $fname file name of the image file
1637 * @access public
1638 */
1639 function wfImageDir( $fname ) {
1640 global $wgUploadDirectory, $wgHashedUploadDirectory;
1641
1642 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1643
1644 $hash = md5( $fname );
1645 $oldumask = umask(0);
1646 $dest = $wgUploadDirectory . '/' . $hash{0};
1647 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1648 $dest .= '/' . substr( $hash, 0, 2 );
1649 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1650
1651 umask( $oldumask );
1652 return $dest;
1653 }
1654
1655 /**
1656 * Returns the image directory of an image's thubnail
1657 * If the directory does not exist, it is created.
1658 * The result is an absolute path.
1659 *
1660 * This function is called from thumb.php before Setup.php is included
1661 *
1662 * @param string $fname file name of the original image file
1663 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1664 * @param boolean $shared (optional) use the shared upload directory
1665 * @access public
1666 */
1667 function wfImageThumbDir( $fname, $shared = false ) {
1668 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1669 if ( Image::isHashed( $shared ) ) {
1670 $dir = "$base/$fname";
1671
1672 if ( !is_dir( $base ) ) {
1673 $oldumask = umask(0);
1674 @mkdir( $base, 0777 );
1675 umask( $oldumask );
1676 }
1677
1678 if ( ! is_dir( $dir ) ) {
1679 if ( is_file( $dir ) ) {
1680 // Old thumbnail in the way of directory creation, kill it
1681 unlink( $dir );
1682 }
1683 $oldumask = umask(0);
1684 @mkdir( $dir, 0777 );
1685 umask( $oldumask );
1686 }
1687 } else {
1688 $dir = $base;
1689 }
1690
1691 return $dir;
1692 }
1693
1694 /**
1695 * Old thumbnail directory, kept for conversion
1696 */
1697 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1698 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1699 }
1700
1701 /**
1702 * Returns the image directory of an image's old version
1703 * If the directory does not exist, it is created.
1704 * The result is an absolute path.
1705 *
1706 * This function is called from thumb.php before Setup.php is included
1707 *
1708 * @param string $fname file name of the thumbnail file, including file size prefix
1709 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1710 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1711 * @access public
1712 */
1713 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1714 global $wgUploadDirectory, $wgHashedUploadDirectory,
1715 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1716 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1717 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1718 if (!$hashdir) { return $dir.'/'.$subdir; }
1719 $hash = md5( $fname );
1720 $oldumask = umask(0);
1721
1722 # Suppress warning messages here; if the file itself can't
1723 # be written we'll worry about it then.
1724 wfSuppressWarnings();
1725
1726 $archive = $dir.'/'.$subdir;
1727 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1728 $archive .= '/' . $hash{0};
1729 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1730 $archive .= '/' . substr( $hash, 0, 2 );
1731 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1732
1733 wfRestoreWarnings();
1734 umask( $oldumask );
1735 return $archive;
1736 }
1737
1738
1739 /*
1740 * Return the hash path component of an image path (URL or filesystem),
1741 * e.g. "/3/3c/", or just "/" if hashing is not used.
1742 *
1743 * @param $dbkey The filesystem / database name of the file
1744 * @param $fromSharedDirectory Use the shared file repository? It may
1745 * use different hash settings from the local one.
1746 */
1747 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1748 if( Image::isHashed( $fromSharedDirectory ) ) {
1749 $hash = md5($dbkey);
1750 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1751 } else {
1752 return '/';
1753 }
1754 }
1755
1756 /**
1757 * Returns the image URL of an image's old version
1758 *
1759 * @param string $fname file name of the image file
1760 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1761 * @access public
1762 */
1763 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1764 global $wgUploadPath, $wgHashedUploadDirectory;
1765
1766 if ($wgHashedUploadDirectory) {
1767 $hash = md5( substr( $name, 15) );
1768 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1769 substr( $hash, 0, 2 ) . '/'.$name;
1770 } else {
1771 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1772 }
1773 return wfUrlencode($url);
1774 }
1775
1776 /**
1777 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1778 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1779 *
1780 * @param string $length
1781 * @return int Length in pixels
1782 */
1783 function wfScaleSVGUnit( $length ) {
1784 static $unitLength = array(
1785 'px' => 1.0,
1786 'pt' => 1.25,
1787 'pc' => 15.0,
1788 'mm' => 3.543307,
1789 'cm' => 35.43307,
1790 'in' => 90.0,
1791 '' => 1.0, // "User units" pixels by default
1792 '%' => 2.0, // Fake it!
1793 );
1794 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1795 $length = floatval( $matches[1] );
1796 $unit = $matches[2];
1797 return round( $length * $unitLength[$unit] );
1798 } else {
1799 // Assume pixels
1800 return round( floatval( $length ) );
1801 }
1802 }
1803
1804 /**
1805 * Compatible with PHP getimagesize()
1806 * @todo support gzipped SVGZ
1807 * @todo check XML more carefully
1808 * @todo sensible defaults
1809 *
1810 * @param string $filename
1811 * @return array
1812 */
1813 function wfGetSVGsize( $filename ) {
1814 $width = 256;
1815 $height = 256;
1816
1817 // Read a chunk of the file
1818 $f = fopen( $filename, "rt" );
1819 if( !$f ) return false;
1820 $chunk = fread( $f, 4096 );
1821 fclose( $f );
1822
1823 // Uber-crappy hack! Run through a real XML parser.
1824 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1825 return false;
1826 }
1827 $tag = $matches[1];
1828 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1829 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1830 }
1831 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1832 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1833 }
1834
1835 return array( $width, $height, 'SVG',
1836 "width=\"$width\" height=\"$height\"" );
1837 }
1838
1839 /**
1840 * Determine if an image exists on the 'bad image list'
1841 *
1842 * @param string $name The image to check
1843 * @return bool
1844 */
1845 function wfIsBadImage( $name ) {
1846 global $wgContLang;
1847 static $titleList = false;
1848 if ( $titleList === false ) {
1849 $titleList = array();
1850
1851 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1852 foreach ( $lines as $line ) {
1853 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1854 $t = Title::newFromText( $m[1] );
1855 $titleList[$t->getDBkey()] = 1;
1856 }
1857 }
1858 }
1859
1860 return array_key_exists( $name, $titleList );
1861 }
1862
1863
1864
1865 /**
1866 * Wrapper class for thumbnail images
1867 * @package MediaWiki
1868 */
1869 class ThumbnailImage {
1870 /**
1871 * @param string $path Filesystem path to the thumb
1872 * @param string $url URL path to the thumb
1873 * @access private
1874 */
1875 function ThumbnailImage( $url, $width, $height, $path = false ) {
1876 $this->url = $url;
1877 $this->width = round( $width );
1878 $this->height = round( $height );
1879 # These should be integers when they get here.
1880 # If not, there's a bug somewhere. But let's at
1881 # least produce valid HTML code regardless.
1882 $this->path = $path;
1883 }
1884
1885 /**
1886 * @return string The thumbnail URL
1887 */
1888 function getUrl() {
1889 return $this->url;
1890 }
1891
1892 /**
1893 * Return HTML <img ... /> tag for the thumbnail, will include
1894 * width and height attributes and a blank alt text (as required).
1895 *
1896 * You can set or override additional attributes by passing an
1897 * associative array of name => data pairs. The data will be escaped
1898 * for HTML output, so should be in plaintext.
1899 *
1900 * @param array $attribs
1901 * @return string
1902 * @access public
1903 */
1904 function toHtml( $attribs = array() ) {
1905 $attribs['src'] = $this->url;
1906 $attribs['width'] = $this->width;
1907 $attribs['height'] = $this->height;
1908 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1909
1910 $html = '<img ';
1911 foreach( $attribs as $name => $data ) {
1912 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1913 }
1914 $html .= '/>';
1915 return $html;
1916 }
1917
1918 }
1919
1920 /**
1921 * Calculate the largest thumbnail width for a given original file size
1922 * such that the thumbnail's height is at most $maxHeight.
1923 * @param int $boxWidth
1924 * @param int $boxHeight
1925 * @param int $maxHeight
1926 * @return int
1927 */
1928 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
1929 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
1930 $roundedUp = ceil( $idealWidth );
1931 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight )
1932 return floor( $idealWidth );
1933 else
1934 return $roundedUp;
1935 }
1936
1937 ?>